package study.reactive.springboot.webflux.auth;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import study.reactive.springboot.webflux.support.utils.WebUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
//@Component
@Order(1)
public class WatchDogWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        //
        Stopwatch stopwatch = Stopwatch.createStarted();
        String path = WebUtils.getHttpRequest(exchange).getURI().getPath();
        log.info("{}", path);
        //
        Mono<Void> result;
        try {
            log.info(">>>>>> try");
            result = chain.filter(exchange).then(Mono.fromRunnable(() -> {
                try {
                    log.info(">>>>>> try try");
                } finally {
                    log.info("[{}] cost time [{}] ms", path, stopwatch.elapsed(TimeUnit.MILLISECONDS));
                    log.info(">>>>>> finally finally");
                }
            }));
        } finally {
            log.info(">>>>>> finally");
        }
        return result;
    }
}
